package com.shao.discovery.impl;

import com.shao.ServiceConfig;
import com.shao.SrpcBootstrap;
import com.shao.channelHandler.watch.UpAndDownWatcher;
import com.shao.constant.ZookeeperCons;
import com.shao.discovery.AbstractZookeeperRegistry;
import com.shao.discovery.Registry;
import com.shao.exception.DiscoveryException;
import com.shao.utils.network.IpUtils;
import com.shao.utils.zookeeper.ZookeeperNode;
import com.shao.utils.zookeeper.ZookeeperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/10 10:05
 */
@Slf4j
public class ZookeeperRegistry extends AbstractZookeeperRegistry implements Registry {

    private final ZooKeeper zooKeeper;

    public ZookeeperRegistry() {
        zooKeeper = ZookeeperUtils.createZookeeper();
    }

    public ZookeeperRegistry(String connectStringAddr, int timeout) {
        zooKeeper = ZookeeperUtils.createZookeeper(connectStringAddr, timeout);
    }

    @Override
    public void registry(ServiceConfig serviceConfig) {
        // 服务名称节点
        String parentNode = ZookeeperCons.BASE_PROVIDERS_PATH + "/" + serviceConfig.getInterface().getName();
        // 持久化服务名称节点
        if (ZookeeperUtils.nodeIsNotExist(zooKeeper, parentNode, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(parentNode, null);
            ZookeeperUtils.createZookeeperNode(zooKeeper, null, zookeeperNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        // 创建本机临时节点--》 ip:port,
        String localTempNode = parentNode + "/" + IpUtils.getIpAddr() + ":" + SrpcBootstrap.getInstance().getConfiguration().getPort();
        if (ZookeeperUtils.nodeIsNotExist(zooKeeper, localTempNode, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(localTempNode, null);
            ZookeeperUtils.createZookeeperNode(zooKeeper, null, zookeeperNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }
    }

    @Override
    public List<InetSocketAddress> lookup(String serviceName) {
        // 拼接服务对应的节点路径
        String serviceNode = ZookeeperCons.BASE_PROVIDERS_PATH + "/" + serviceName;
        // 获取指定节点的子节点
        List<String> childrenList = ZookeeperUtils.getChildren(zooKeeper, serviceNode, new UpAndDownWatcher());

        List<InetSocketAddress> socketAddressesList = childrenList.stream().map(addrStirng -> {
            String host = addrStirng.substring(0, addrStirng.indexOf(":"));
            int port = Integer.parseInt(addrStirng.substring(addrStirng.indexOf(":") + 1));
            return new InetSocketAddress(host, port);
        }).toList();
        if (socketAddressesList.isEmpty()) {
            log.error("节点【{}】不存在", serviceNode);
            throw new DiscoveryException();
        }
        return socketAddressesList;
    }
}
